<template>
  <van-pull-refresh v-model="loadState.pullLoading" :disabled="pullDisabled" @refresh="onRefresh">
    <virtual-list ref="vsl" class="my_scrollbar h-full overflow-y-auto" :data-key="'conversationID'"
      :data-sources="conversationStore.storeConversationList" :data-component="ConversationListItemVue"
      :estimate-size="88" @tobottom="onBottom" @scroll="onScoll" />
  </van-pull-refresh>
</template>

<script setup lang='ts'>
import useConversationStore from '@/store/modules/conversation';
import VirtualList from '@components/VirtualList';
import ConversationListItemVue from './ConversationListItem.vue';
import { useRoute, useRouter } from 'vue-router';
import { SessionType } from '@openim/wasm-client-sdk';
import { watch } from 'vue';
import { IMSDK } from "@/utils/imCommon";
import useCreateNomalMessage from "@pages/conversation/chat/components/ChatFooter/useCreateNomalMessage";
import useSendMessage from "@/hooks/useSendMessage";
import useConversationToggle from '@/hooks/useConversationToggle';
const { toSpecifiedConversation } = useConversationToggle();
const route = useRoute();
const router = useRouter();
const conversationStore = useConversationStore();
const loadState = reactive({
  loading: false,
  pullLoading: false,
  hasMore: true
});
const pullDisabled = ref(false)
const messageContent = ref('')
const { switchNomalMessage } = useCreateNomalMessage({
  messageContent,
});
const { sendMessage } = useSendMessage();
import { searchUserInfoByBusiness } from "@/api/user";
import useContactStore from "@/store/modules/contact";
const contactStore = useContactStore();

// onMounted(() => {
//   handleConversationFromUrl();
// });

// 监听会话列表变化
watch(() => conversationStore.storeConversationList, (list) => {
    handleConversationFromUrl();
}, { immediate: true })

const searchUsers = async (value: string) => {
  try {
    const { data: { users, total } } = await searchUserInfoByBusiness(value);
    console.log("zsq-total", total)
    console.log("zsq-users", users)
    const businessData = users[0];
    businessData.userID = value
    console.log("zsq-value", value)
    console.log("zsq-businessData", businessData)
    const { data } = await IMSDK.getUsersInfo([businessData.userID]);
    console.log("zsq-businessData", data)
    const imData = data[0]?.friendInfo ?? data[0]?.publicInfo ?? {};
    const info = {
      ...imData,
      ...businessData,
    };
    contactStore.setUserCardData({
      baseInfo: info,
    });
    // toConversation()
  } catch (error) { }
};

const toConversation = () => {
  console.log("zsq-contactStore", contactStore.storeUserCardData.baseInfo?.userID!)
  toSpecifiedConversation({
    sourceID: contactStore.storeUserCardData.baseInfo?.userID!,
    sessionType: SessionType.Single
  })
}


const handleConversationFromUrl = async () => {
  const conversationID = route.query.conversationID as string;
  console.log("zsq-conversation-ID", conversationID)
  if (conversationID) {
    const conversation = conversationStore.storeConversationList.find(
      conv => conv.conversationID === conversationID
    );

    if (conversation) {
      conversationStore.updateCurrentConversation(conversation);
      const path = conversation.conversationType === SessionType.Notification
        ? 'notifyMessageList'
        : 'chat';
      router.push(path);
    } else {
      // 从会话ID中提取用户ID
      console.log("zsq-conversationID:" + conversationID.split('_')[1])
      const userID = conversationID.split('_')[1];
      searchUsers(userID)
      if (userID) {
        try {
          // 创建单聊会话
          // const { data: conversation } = await IMSDK.createConversation({
          //   sourceID: userID,
          //   sessionType: SessionType.Single
          // });
          // const message = await switchNomalMessage();
          // if (message) {
            // message.recvID = conversationID.split('_')[1]
            // console.log("zsq-message" + JSON.stringify(message))
            // const options = {
            //     recvID: conversationID.split('_')[1] ?? conversationID.split('_')[1] ?? "",
            //     message,
            // };
            // const { data: successMessage } = await IMSDK.sendMessage(options);
            // console.log("successMessage:" + successMessage)
          // }

          // 更新当前会话
          conversationStore.updateCurrentConversation(conversation);

          // 跳转到聊天页面
          router.push('chat');
        } catch (error) {
          console.error(error);
        }
      }
    }
  }
}

onMounted(async () => {
  await conversationStore.getConversationListFromReq();
});

const onBottom = async () => {
  if (loadState.hasMore && !loadState.loading) {
    loadState.loading = true
    loadState.hasMore = await conversationStore.getConversationListFromReq(true)
    loadState.loading = false
  }
}

const onScoll = (e: any) => {
  pullDisabled.value = e.target.scrollTop > 0
}

const onRefresh = async () => {
  await conversationStore.getConversationListFromReq()
  loadState.pullLoading = false
}
</script>

<style lang='scss' scoped>
.van-pull-refresh {
  flex: 1;
}
</style>
